package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 用户服务
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService, UserDetailsService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;


    //根据用户名查询数据库获取用户信息和关联的角色信息，同时需要查询角色关联的权限信息
    public User findByUsername(String username) {
        User user = userDao.findByUsername(username);//查询用户基本信息，不包含用户的角色
        if (user == null) {
            return null;
        }
        Integer userId = user.getId();
        //根据用户ID查询对应的角色
        Set<Role> roles = roleDao.findByUserId(userId);
        for (Role role : roles) {
            Integer roleId = role.getId();
            //根据角色ID查询关联的权限
            Set<Permission> permissions = permissionDao.findByRoleId(roleId);
            role.setPermissions(permissions);//让角色关联权限
        }
        user.setRoles(roles);//让用户关联角色
        return user;
    }


    @Override
    public PageResult findByPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();//获得当前页
        Integer pageSize = queryPageBean.getPageSize();//获得每页展示数据条数
        String queryString = queryPageBean.getQueryString();//获取查询条件(用户名)

        PageHelper.startPage(currentPage, pageSize);
        Page<User> page = userDao.findByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public void addUser(User user, Integer[] roleIds) {
        String password = user.getPassword();
        String encode = passwordEncoder.encode(password);
        user.setPassword(encode);
        userDao.add(user);
        //添加用户之后添加关联关系
        //获得新添加的UserId
        Integer userId = user.getId();
        for (Integer roleId : roleIds) {
            Map<String, Integer> map = new HashMap<>();
            map.put("userId", userId);
            map.put("roleId", roleId);
            userDao.setUserAndRole(map);
        }

    }

    /**
     * 根据用户id删除用户
     *
     * @param id
     */
    @Override
    public void deleteById(int id) {
        //首先判断此数据是否绑定关联关系
        Long count = userDao.selectUserAndRoleByUserId(id);
        if (count != 0) {
            //存在关联关系
            //删除关系表中的数据
            userDao.deleteRelationsOfUserAndRole(id);
        }
        //不存在关联关系
        userDao.deleteUser(id);
    }

    @Override
    public User findById(int id) {
        User user = userDao.findUserById(id);
        return user;
    }

    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        return null;
    }

    //编辑用户
    @Override
    public void edit(User user, Integer[] roleIds) {
        String password = user.getPassword();
        if (password != null) {
            user.setPassword(passwordEncoder.encode(password));
        }
        userDao.edit(user);//修改用户信息
        Integer userId = user.getId();
        userDao.deleteRelationsOfUserAndRole(userId);//删除与角色的关联表数据
        this.addMethod(userId, roleIds);
    }


    private void addMethod(Integer userId, Integer[] roleIds) {
        if (roleIds != null && roleIds.length > 0) {
            for (Integer roleId : roleIds) {
                Map map = new HashMap();
                map.put("userId", userId);
                map.put("roleId", roleId);
                userDao.setUserAndRole(map);//添加与角色的关联表数据
            }
        }

    }
}
